package com.wcsy.myblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import com.wcsy.myblog.entity.JsonResult;
import com.wcsy.myblog.entity.Qq;
import com.wcsy.myblog.entity.User;
import com.wcsy.myblog.service.IQQService;
import com.wcsy.myblog.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;

/**
 * qq登陆
 */
@RestController
@CrossOrigin
@Api(description = "qq登陆")
@ApiModel
public class QQController {
    @Autowired
    IQQService iqqService;
    @Autowired
    IUserService iUserService;
    @Autowired
    HttpSession session;

    /**
     * @apiNote 用户直接登陆qq，如果没有绑定用户表，则输入已注册用户信息，如果没注册就去注册
     * @return
     */
    @ApiOperation("将qq和用户绑定,先登陆qq，后绑定用户")
    @GetMapping("insertUser")
    public JsonResult insert(@RequestBody User user){

        UsernamePasswordToken token = new UsernamePasswordToken(user.getPhNumber(),user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            //此时说明输入的账号密码是对的
            subject.login(token);
            //讲qq和用户绑定在一起
            iqqService.insertQq();
           return new JsonResult(200,"绑定成功","");
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return new JsonResult(500,"绑定失败","");
    }

    /**
     * @apiNote 先登录用户，后绑定qq
     * @return
     */
    @ApiOperation("将用户和qq绑定,先登陆用户，后绑定qq")
    @GetMapping("insertQq")
    public JsonResult insertQq(){
        User user = (User) session.getAttribute("user");
        String openID = (String) session.getAttribute("openID");
        try {
            iqqService.insertQq((int)user.getUserId(),openID);
            return new JsonResult(200,"绑定成功","");
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(500,"绑定失败","");
        }
    }
    /**
     * 请求QQ登录
     */
    @GetMapping("/loginByQQ")
    public void loginByQQ(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=utf-8");

        try {
            response.sendRedirect(new Oauth().getAuthorizeURL(request));
            System.out.println("请求QQ登录,开始跳转...");
        } catch (QQConnectException | IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 登出
     */
    @GetMapping("/qqlogout")
    public JsonResult qqlogout(){
        session.removeAttribute("user");
        session.removeAttribute("openID");
        session.removeAttribute("demo_access_token");
        session.removeAttribute("demo_token_expirein");
        return new JsonResult(200,"注销成功","");
    }
    /**
     * QQ登录回调地址
     *
     * @return
     */
    @GetMapping("/connection")
    public JsonResult connection(HttpServletRequest request, HttpServletResponse response, Map<String,Object> map) {
        try {
            AccessToken accessTokenObj = (new Oauth()).getAccessTokenByRequest(request);
            String accessToken = null, openID = null;
            long tokenExpireIn = 0L;
            if ("".equals(accessTokenObj.getAccessToken())) {
                System.out.println("登录失败:没有获取到响应参数");
                return new JsonResult(500,"登录失败:没有获取到响应参数","");
//                return "accessTokenObj=>" + accessTokenObj + "; accessToken" + accessTokenObj.getAccessToken();
            } else {
                accessToken = accessTokenObj.getAccessToken();
                tokenExpireIn = accessTokenObj.getExpireIn();
                System.out.println("accessToken" + accessToken);
                request.getSession().setAttribute("demo_access_token", accessToken);
                request.getSession().setAttribute("demo_token_expirein", String.valueOf(tokenExpireIn));

                // 利用获取到的accessToken 去获取当前用的openid -------- start
                OpenID openIDObj = new OpenID(accessToken);
                openID = openIDObj.getUserOpenID();
                request.getSession().setAttribute("openID",openID);
                UserInfo qzoneUserInfo = new UserInfo(accessToken, openID);
                UserInfoBean userInfoBean = qzoneUserInfo.getUserInfo();
                if (userInfoBean.getRet() == 0) {
                    String name = removeNonBmpUnicode(userInfoBean.getNickname());
                    String imgUrl = userInfoBean.getAvatar().getAvatarURL100();
                    map.put("openId", openID);
                    map.put("name", name);
                    map.put("imgUrl", imgUrl);
                   //根据qq标识id获取用户id
                    Qq qq = iqqService.getOne(new QueryWrapper<Qq>().eq("open_id", openID));
                    //根据用户id查出用户
                    User user = iUserService.getOne(new QueryWrapper<User>().eq("user_id", qq.getUserId()));
                    if (user!=null){
                        request.getSession().setAttribute("user",user);
                    }
                  return new JsonResult(200,"登陆成功","");

                }
//                    System.out.println("很抱歉，我们没能正确获取到您的信息，原因是： " + userInfoBean.getMsg());
                return new JsonResult(500,"很抱歉，我们没能正确获取到您的信息","");

            }
        } catch (QQConnectException e) {
            e.printStackTrace();
            return new JsonResult(500,"出现未知错误","");
        }
    }
        /**
         * 处理掉QQ网名中的特殊表情
         * @param str
         * @return
         */
        public String removeNonBmpUnicode(String str) {
            if (str == null) {
                return null;
            }
            str = str.replaceAll("[^\\u0000-\\uFFFF]", "");
            if ("".equals(str)) {
                str = "(* _ *)";
            }
            return str;
        }

}
